package com.imc.platform.demo.service;

import com.imc.platform.base.user.dao.repository.UserRepository;
import com.imc.platform.base.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tanweiping on 2018/7/19.
 */
@Slf4j
@Transactional
@Service
public class UserService {

//    @Cacheable(value = "UserServicefindAll",key="#name")
//    public List<String> findAll(String name){
//        val ss = Arrays.asList("1","2","3");
//        log.info("ss:");
//        return ss;
//    }

    @PersistenceContext
    EntityManager entityManager;


    @Autowired
    UserRepository userRepository;

    public void save(List<User> users){
        //更新
        entityManager.merge(users);
        //userRepository.save(users);
        //entityManager.persist(users);
    }

    public Page<User> lamda(Pageable pageable,User user){
        return userRepository.findAll(
                (root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(user.getId())){
                        predicates.add(criteriaBuilder.equal(root.get("id"),user.getId()));
                    }
                    if(!StringUtils.isEmpty(user.getCityName())){
                        predicates.add(criteriaBuilder.like(root.get("cityId"), "%"+user.getCityName()+"%"));
                    }
                    return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
                },
                pageable);
    }

    @Cacheable(value = "user",keyGenerator="keyGenerator")
    public List<User> findAll(String name){
        List<User> users = userRepository.findAll();
        return users;
    }

    @Cacheable(value = "user",keyGenerator="keyGenerator")
    public Page<User> findAll(Pageable pageable){
        Page<User> users = userRepository.findAll(pageable);
        return users;
    }

    @Cacheable(value = "user",key = "#id")
    public User repositoryfindAll(String id){
       // return userRepository.findUserById(id);
        return null;
    }
}
